package com.wu.config;

import com.wu.error.BusinessException;
import com.wu.error.EnumBusinessError;
import com.wu.response.CommonReturnType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

import static com.wu.constant.Constant.*;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 21:32
 */
@ControllerAdvice
public class BaseExceptionHandler {

    /**
     * 是否开启异常拦截
     */
    @Value("${server.isEnabledExceptionHandler}")
    private Boolean enable;


    /**
     * 定义exceptionHandler解决未被controller层吸收的exception
     * 避免在前端页面抛出异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    private Object exceptionHandler(HttpServletRequest request, Exception e) throws BusinessException {
        HashMap<String, Object> responseData = new HashMap();
        if (Boolean.TRUE.equals(enable)) {
            if (e instanceof BusinessException) {
                BusinessException businessException = (BusinessException) e;
                responseData.put(ERROR_CODE, businessException.getErrorCode());
                responseData.put(ERROR_MSG, businessException.getErrorMsg());
            } else {
                responseData.put(ERROR_CODE, EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
                responseData.put(ERROR_MSG, EnumBusinessError.UNKNOWN_ERROR.getErrorMsg());
            }
        } else {
            e.printStackTrace();
        }
        return CommonReturnType.create(responseData, ERROR_STATUS);
    }
}

